import axios from 'axios';
import navMenus from '../pages/Login/menuData';

// 创建用于认证的axios实例
const authAxios = axios.create({
  baseURL: '/api/pc',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
authAxios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token && config.url !== '/login/check') {
      // 登出等需要认证的请求添加token
      config.headers['Authorization'] = `Bearer ${token}`;
      config.headers['access-token'] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 模拟的游客账号
const guestAccount = {
  username: 'admin',
  password: 'admin',
  token: 'guest-token-12345',
  userinfo: JSON.stringify({
    id: 1,
    name: '游客用户',
    role: 'guest'
  })
};

// 创建菜单数据的深拷贝，避免修改原始对象
const getMenuDataCopy = () => {
  return JSON.parse(JSON.stringify(navMenus));
};

// 登录接口
export const login = async (phone: string, password: string) => {
  try {
    // 检查是否是游客账号
    if (phone === guestAccount.username && password === guestAccount.password) {
      // 返回游客账号的模拟响应，使用深拷贝的菜单数据
      return {
        code: 0,
        msg: '登录成功',
        data: {
          access_token: guestAccount.token,
          nav: getMenuDataCopy(), // 使用深拷贝
        },
        userinfo: guestAccount.userinfo
      };
    }
    
    // 真实登录请求
    const response = await authAxios.post('/login/check', {
      phone,
      password
    });
    return response.data;
  } catch (error) {
    // 如果API请求失败，再次检查是否是游客账号
    if (phone === guestAccount.username && password === guestAccount.password) {
      return {
        code: 0,
        msg: '登录成功',
        data: {
          access_token: guestAccount.token,
          nav: getMenuDataCopy(), // 使用深拷贝
        },
        userinfo: guestAccount.userinfo
      };
    }
    throw error;
  }
};

// 登出接口
export const logout = async () => {
  try {
    // 检查是否是游客账号
    const token = localStorage.getItem('token');
    if (token === guestAccount.token) {
      // 清除本地存储的游客信息
      localStorage.removeItem('token');
      localStorage.removeItem('menuData');
      localStorage.removeItem('userinfo');
      return { code: 0, msg: '登出成功' };
    }
    
    // 真实登出请求
    const response = await authAxios.post('/logout');
    return response.data;
  } catch (error) {
    throw error;
  }
}; 